package com.lanou.moving.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.adapter.LyricAdapter;
import com.lanou.moving.adapter.MusicListAdapter;
import com.lanou.moving.base.BaseActivity;
import com.lanou.moving.base.BaseApplication;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.AlbumPic;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.lrc.LyricDownloadManager;
import com.lanou.moving.lrc.LyricLoadHelper;
import com.lanou.moving.modle.LyricSentence;
import com.lanou.moving.service.MyService;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.utils.Exchange;
import com.lanou.moving.utils.MyConfig;
import com.lanou.moving.view.SelectPopupWindow;
import com.lanou.moving.view.SlideDeleteListView;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.io.File;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by 刘琪 on 15/10/29.
 */

public class PlayMusicActivity extends BaseActivity implements
        View.OnClickListener, CompoundButton.OnCheckedChangeListener, SeekBar.OnSeekBarChangeListener,
        SlideDeleteListView.RemoveListener {
    private Toolbar play_toolbar;
    private TextView end_time;// 音乐时长
    private TextView start_time;
    private ImageView play_state;// 播放状态
    private ImageView pre;// 上一首
    private ImageView next;// 上一首
    private Toast mToast;

    // 获得数据
    private List<MusicInfo> musicInfoList;

    private CheckBox play;//播放、暂停
    private CircleImageView albumPic;//专辑图片
    private Animation animation;//旋转动画

    // 获取专辑图片
    private String url;
    private StringRequestUtf request;
    private VolleySingleton volleySingleton;


    // 播放状态
    private int playState = 0;
    // 播放状态的图片
    private int[] imgs = {R.mipmap.play_icn_loop, R.mipmap.play_icn_one, R.mipmap.play_icn_random};

    // 进度条
    private SeekBar seekBar;
    private Handler handler;//post  Runnable
    private HandlerThread handlerThread;//改变播放时间
    private Handler mHandler;//发消息

    // 播放列表
    private View view;
    private ImageView play_music_list;

    private static final String TAG = "PlayMusicActivity";

    //    private CheckBox lyric_checkBox;//歌词按钮
    private ListView lyricshow;//显示歌词
    private LyricAdapter mLyricAdapter;
    private LyricDownloadManager lyricDownloadManager;
    private LyricLoadHelper mLyricLoadHelper;
    private int mScreenWidth;
    private boolean isExit = false; // 判断歌词文件是否存在

    // 最近播放
    private RecentlyPlayDao recentlyPlayDao;

    private MyService.MediaBinder mediaBinder;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("qiqi", "" + (service instanceof MyService.MediaBinder));
            if (service instanceof MyService.MediaBinder) {
                mediaBinder = (MyService.MediaBinder) service;
                new SeekBarThread().start();
                EventBus.getDefault().post(new MyEventBus.OpenMusic(true));
//                loadLyricByHand(mediaBinder.getSongName(), mediaBinder.getSingerName());
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private MusicListAdapter adapter;
    private TextView current_music;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);
        BaseApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        volleySingleton = VolleySingleton.getInstance(this);
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();

        // 绑定服务
        Intent service = new Intent(this, MyService.class);
        bindService(service, connection, BIND_AUTO_CREATE);
        same();

        mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);

        handler = new Handler();
        handlerThread = new HandlerThread("新伟哥哥");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper()) {
            // 接收消息
            public void handleMessage(Message msg) {
                //执行改变时间的方法(每100毫秒发送一条空Message)
                runBack();
                mHandler.sendEmptyMessageDelayed(1, 100);
            }
        };

    }


    private void setMusicInfo() {
        seekBar.setMax(mediaBinder.getMax());
        end_time.setText(Exchange.formatTime((long) mediaBinder.getMax()));
        play_toolbar.setTitle(mediaBinder.getSongName());
        play_toolbar.setSubtitle(mediaBinder.getSingerName());
        play.setChecked(true);
        Log.i(TAG, mediaBinder.getResouce());
        if (mediaBinder.getResouce().equals("网络")) {
            initNetData();
        }
    }

    private void runBack() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (mediaBinder != null) {
                    mLyricLoadHelper.notifyTime(mediaBinder.getCurrentPosition());
                    start_time.setText(Exchange.formatTime((long) mediaBinder.getCurrentPosition()));
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }

    // 初始化中相同的部分
    public void same() {
        play_toolbar = (Toolbar) findViewById(R.id.play_toolbar);
        play_toolbar.setNavigationIcon(R.mipmap.mine_go_back_normal);
        play_toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        play_toolbar.setTitleTextColor(0xffffffff);
        play_toolbar.setSubtitleTextColor(0xffffffff);
        // 进度
        start_time = (TextView) findViewById(R.id.start_time);
        // 歌曲总时长
        end_time = (TextView) findViewById(R.id.end_time);
        // 播放状态
        play_state = (ImageView) findViewById(R.id.playState);
        play_state.setBackgroundResource(imgs[playState]);
        play_state.setOnClickListener(this);
        // 上一曲
        pre = (ImageView) findViewById(R.id.pre);
        pre.setOnClickListener(this);
        // 下一曲
        next = (ImageView) findViewById(R.id.next);
        next.setOnClickListener(this);
        // 播放与暂停
        play = (CheckBox) findViewById(R.id.play);
        play.setOnCheckedChangeListener(this);
        // 专辑图片
        albumPic = (CircleImageView) findViewById(R.id.albumPic);
        // 播放列表
        play_music_list = (ImageView) findViewById(R.id.play_music_list);
        play_music_list.setOnClickListener(this);
        // 进度条
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        if (mediaBinder != null) {
            seekBar.setMax(mediaBinder.getMax());
        }
        seekBar.setOnSeekBarChangeListener(this);
        // 旋转动画
        animation = AnimationUtils.loadAnimation(this, R.anim.play_rotate);
        LinearInterpolator linear = new LinearInterpolator();
        animation.setInterpolator(linear);
        albumPic.startAnimation(animation);


        mLyricLoadHelper = new LyricLoadHelper();
        lyricDownloadManager = new LyricDownloadManager();
//        lyric_checkBox = (CheckBox) findViewById(R.id.lyric_checkBox);//歌词下载
        lyricshow = (ListView) findViewById(R.id.lyricshow);//显示歌词
        mLyricAdapter = new LyricAdapter(this);

        DisplayMetrics metric = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenWidth = metric.widthPixels;
        mLyricLoadHelper.setLyricListener(mLyricListener);

    }


    // 网络音乐
    private void initNetData() {
        if (mediaBinder.getAlbumId() == 0) {

        } else {
            url = URL.ALBUM_PIC_START + mediaBinder.getAlbumId() + URL.ALBUM_PIC_END;
            request = new StringRequestUtf(url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    AlbumPic data = gson.fromJson(response, AlbumPic.class);
                    if (data != null) {
                        Picasso.with(PlayMusicActivity.this).load(data.getData().getPicUrl())
                                .placeholder(R.mipmap.play_music).error(R.mipmap.play_music).into(albumPic);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(request);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(1);
        playState = MyConfig.getSharePreInt(PlayMusicActivity.this, "playMode", "playState");
        play_state.setBackgroundResource(imgs[playState]);
        EventBus.getDefault().post(new MyEventBus.PlayMode(playState));
    }

    public void onEventMainThread(MyEventBus.PlayControl playControl) {
        setMusicInfo();
//        isExit = false;
        // 取得歌曲同目录下的歌词文件绝对路径
//        String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
//        mLyricLoadHelper.loadLyric(lyricFilePath);
        loadLyricByHand(mediaBinder.getSongName(), mediaBinder.getSingerName());
        current_music.setText(mediaBinder.getSongName());
        RecentlyPlay recentlyPlay = new RecentlyPlay();
        recentlyPlay.setSongName(mediaBinder.getSongName());
        recentlyPlay.setPlayUrl(mediaBinder.getUrl());
        recentlyPlay.setSingerName(mediaBinder.getSingerName());
        recentlyPlay.setDuration((long) mediaBinder.getMax());
        recentlyPlay.setSongId(mediaBinder.getSongId());
        recentlyPlay.setResource("网络");
        recentlyPlayDao.insertOrReplace(recentlyPlay);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pre:
                EventBus.getDefault().post(new MyEventBus.PlayControl(2));
                break;
            case R.id.next:
                EventBus.getDefault().post(new MyEventBus.PlayControl(3));
                break;
            case R.id.playState:
                playState++;
                if (playState > 2) {
                    playState = 0;
                }
                EventBus.getDefault().post(new MyEventBus.PlayMode(playState));
                // 改变图片
                play_state.setBackgroundResource(imgs[playState]);
                MyConfig.putSharePre(PlayMusicActivity.this, "playMode", "playState", playState);
                break;
            case R.id.play_music_list:
                // 加载listView布局
                view = LayoutInflater.from(PlayMusicActivity.this).inflate(R.layout.music_list, null);
                current_music = (TextView) view.findViewById(R.id.current_music);
                SlideDeleteListView listView = (SlideDeleteListView) view.findViewById(R.id.music_list);
                // 给listView设置滑动删除监听
                listView.setRemoveListener(this);
                // 取消listView的点击效果
                listView.setSelector(new ColorDrawable(Color.TRANSPARENT));
                // 获取播放列表中的数据
                musicInfoList = mediaBinder.getMusicInfoList();
                adapter = new MusicListAdapter(musicInfoList);
                // 当前播放的音乐
                current_music.setText(mediaBinder.getSongName());
                listView.setAdapter(adapter);
                // 弹出播放列表
                SelectPopupWindow popupWindow = new SelectPopupWindow
                        (PlayMusicActivity.this, onItemClickListener, view);
                popupWindow.showAtLocation(play_music_list, Gravity.RIGHT, 0, 0);
                break;
        }
    }

    // 播放列表的点击监听
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            EventBus.getDefault().post(new MyEventBus.ChangeMusic(position));
            current_music.setText(mediaBinder.getSongName());
        }
    };

    public void onEventMainThread(MyEventBus.ChangeMusic changeMusic) {
        setMusicInfo();
//        isExit = false;
//        // 取得歌曲同目录下的歌词文件绝对路径
//        String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
//        mLyricLoadHelper.loadLyric(lyricFilePath);
        loadLyricByHand(mediaBinder.getSongName(), mediaBinder.getSingerName());
    }

    /**
     * 播放列表的滑动删除监听
     *
     * @param direction 滑动方向
     * @param position  滑动行布局的位置
     */
    @Override
    public void removeItem(SlideDeleteListView.RemoveDirection direction, int position) {
        // 如果删除的音乐当前正在播放,播放下一首
        if (position == mediaBinder.getPosition()) {
            EventBus.getDefault().post(new MyEventBus.PlayControl(3));
        }
        // 从播放列表中删除音乐
        musicInfoList.remove(position);
        // 通知适配器数据改变
        adapter.notifyDataSetChanged();
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + mediaBinder.getSongName() + ".lrc";
        mLyricLoadHelper.loadLyric(lyricFilePath);
    }

    public void onEvent(MyEventBus.PlayMusic playMusic) {
        switch (playMusic.getWhat()) {
            case 2:// 暂停
                play.setChecked(false);
                break;
            case 3:// 播放
                play.setChecked(true);
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // 播放
            if (isExit) {

            } else {
                animation = AnimationUtils.loadAnimation(this, R.anim.play_rotate);
                LinearInterpolator linear = new LinearInterpolator();
                animation.setInterpolator(linear);
                albumPic.startAnimation(animation);
            }
            EventBus.getDefault().post(new MyEventBus.PlayMusic(3));
        } else {
            // 暂停
            EventBus.getDefault().post(new MyEventBus.PlayMusic(2));
            albumPic.clearAnimation();
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        if (mediaBinder != null) {
            mediaBinder.seekTo(progress);
        }
    }

    public class SeekBarThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (mediaBinder != null) {
                seekBar.setProgress(mediaBinder.getCurrentPosition());
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void onEventMainThread(MyEventBus.GetLrcCount getLrcCount) {
        switch (getLrcCount.getCount()) {
            case 0:
//                Toast.makeText(PlayMusicActivity.this, "抱歉, 没有解析到指定歌词", Toast.LENGTH_LONG).show();
                isExit = false;
                mToast.setText("抱歉, 没有解析到指定歌词");
                mToast.show();
//                isExit = false;
                lyricshow.setVisibility(View.GONE);
                albumPic.setVisibility(View.VISIBLE);
                // 旋转动画
                animation = AnimationUtils.loadAnimation(PlayMusicActivity.this, R.anim.play_rotate);
                LinearInterpolator linear = new LinearInterpolator();
                animation.setInterpolator(linear);
                albumPic.startAnimation(animation);
                break;
            case 1:
                isExit = true;
                Log.i(TAG, "有歌词");
//                isExit = true;
                lyricshow.setVisibility(View.VISIBLE);
                albumPic.clearAnimation();
                albumPic.setVisibility(View.GONE);
                lyricshow.setAdapter(mLyricAdapter);
                lyricshow.startAnimation(AnimationUtils.loadAnimation(PlayMusicActivity.this,
                        android.R.anim.fade_in));
                albumPic.clearAnimation();
                albumPic.setVisibility(View.GONE);
                break;
        }
    }


        public void onEventMainThread (MyEventBus.RefreshUI refreshUI){
            if (refreshUI.isPlaying()) {
                Log.i(TAG, "正在播放");
                setMusicInfo();
                loadLyricByHand(mediaBinder.getSongName(), mediaBinder.getSingerName());
            }
        }



    private void loadLyricByHand(String musicName, String artist) {
        // 取得歌曲同目录下的歌词文件绝对路径
        String lyricFilePath = BaseApplication.lrcPath + "/" + musicName + ".lrc";
        File lyricfile = new File(lyricFilePath);

        if (lyricfile.exists()) {
            isExit = true;
            // 本地有歌词，直接读取
            // Log.i(TAG, "loadLyric()--->本地有歌词，直接读取");
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else {
            // 尝试网络获取歌词
            Log.i("", "loadLyric()--->本地无歌词，尝试从网络获取");
            new LyricDownloadAsyncTask().execute(musicName, artist);

        }
    }


    class LyricDownloadAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            // 从网络获取歌词，然后保存到本地
            String lyricFilePath = lyricDownloadManager.searchLyricFromWeb(
                    params[0], params[1], mediaBinder.getSongName());
            // 返回本地歌词路径
            return lyricFilePath;
        }

        @Override
        protected void onPostExecute(String result) {
            // Log.i(TAG, "网络获取歌词完毕，歌词保存路径:" + result);
            // 读取保存到本地的歌曲
            mLyricLoadHelper.loadLyric(result);
        }
    }

    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            // Log.i(TAG, "onLyricLoaded");
            if (lyricSentences != null) {
                // Log.i(TAG, "onLyricLoaded--->歌词句子数目=" + lyricSentences.size()
                // + ",当前句子索引=" + index);
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
                // mHandler.sendMessageDelayed(
                // Message.obtain(null, MSG_SET_LYRIC_INDEX, index, 0),
                // 100);
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            // Log.i(TAG, "onLyricSentenceChanged--->当前句子索引=" +
            // indexOfCurSentence);
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            lyricshow.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lyricshow.getHeight() / 2, 500);
        }
    };

}


